<template>
    <div class="admin-instructor">
      <!-- 工具栏 -->
      <el-card class="search-bar">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="search.name" placeholder="按姓名搜索" clearable />
          </el-col>
          <el-col :span="6">
            <el-input v-model="search.phone" placeholder="按手机号搜索" clearable />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="searchInstructors">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="success" @click="openAddDialog">+ 新增教练</el-button>
          </el-col>
        </el-row>
      </el-card>
  
      <!-- 教练列表 -->
      <el-table :data="instructors" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名" width="150"></el-table-column>
        <el-table-column prop="gender" label="性别" width="100">
          <template slot-scope="{ row }">
            {{ row.gender === '男' ? '♂' : '♀' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone_number" label="联系电话" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱">
          <template slot-scope="{ row }">
            <a :href="`mailto:${row.email}`">{{ row.email }}</a>
          </template>
        </el-table-column>
        <el-table-column prop="teaching_style" label="教学风格"></el-table-column>
        <el-table-column prop="available_times" label="可预约时段"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="{ row }">
            <el-button size="mini" @click="openEditDialog(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteInstructor(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <el-pagination
        background
        layout="total, prev, pager, next"
        :total="total"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
  
      <!-- 表单弹窗 -->
      <el-dialog :title="form.id ? '编辑教练' : '新增教练'" :visible.sync="dialogVisible">
        <el-form ref="instructorForm" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="电话号码" prop="phone_number">
            <el-input v-model="form.phone_number" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
          <el-form-item label="教学风格" prop="teaching_style">
            <el-input type="textarea" v-model="form.teaching_style" :rows="3" />
          </el-form-item>
          <el-form-item label="可预约时段" prop="available_times">
            <el-input type="textarea" v-model="form.available_times" :rows="3" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        // 教练列表相关
        instructors: [],
        total: 0,
        currentPage: 1,
        pageSize: 10,
  
        // 搜索条件
        search: {
          name: '',
          phone: ''
        },
  
        // 弹窗控制
        dialogVisible: false,
        
        // 表单数据
        form: {
          id: null,
          name: '',
          gender: '男',
          phone_number: '',
          email: '',
          teaching_style: '',
          available_times: ''
        },
  
        // 表单验证规则
        rules: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
          ],
          phone_number: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '邮箱格式不正确', trigger: 'blur' }
          ]
        }
      };
    },
    created() {
      //this.fetchInstructors();
    },
    methods: {
      async fetchInstructors() {
        try {
          const response = await axios.get('/api/admin/instructors', {
            params: {
              page: this.currentPage,
              per_page: this.pageSize,
              name: this.search.name,
              phone: this.search.phone
            }
          });
          this.instructors = response.data.items;
          this.total = response.data.total;
        } catch (error) {
          console.error('获取教练数据失败:', error);
          this.$message.error('获取教练数据失败');
        }
      },
      
      // 搜索
      searchInstructors() {
        this.currentPage = 1;
        this.fetchInstructors();
      },
  
      // 重置搜索
      resetSearch() {
        this.search = {
          name: '',
          phone: ''
        };
        this.currentPage = 1;
        this.fetchInstructors();
      },
  
      // 分页切换
      handlePageChange(page) {
        this.currentPage = page;
        this.fetchInstructors();
      },
  
      // 打开新增窗口
      openAddDialog() {
        this.form = {
          id: null,
          name: '',
          gender: '男',
          phone_number: '',
          email: '',
          teaching_style: '',
          available_times: ''
        };
        this.dialogVisible = true;
      },
  
      // 打开编辑窗口
      openEditDialog(instructor) {
        this.form = {...instructor};
        this.dialogVisible = true;
      },
  
      // 提交表单
      submitForm() {
        this.$refs.instructorForm.validate(async (valid) => {
          if (!valid) {
            this.$message.error('请检查表单输入');
            return;
          }
  
          try {
            if (this.form.id) {
              // 更新
              await axios.put(`/api/admin/instructors/${this.form.id}`, this.form);
              this.$message.success('更新成功');
            } else {
              // 新增
              const response = await axios.post('/api/admin/instructors', this.form);
              this.form.id = response.data.id;
              this.$message.success('新增成功');
            }
            
            this.dialogVisible = false;
            this.fetchInstructors();
          } catch (error) {
            console.error('操作失败:', error);
            this.$message.error('操作失败');
          }
        });
      },
  
      // 删除教练
      async deleteInstructor(id) {
        try {
          await this.$confirm('确定要删除该教练吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          });
  
          await axios.delete(`/api/admin/instructors/${id}`);
          this.$message.success('删除成功');
          this.fetchInstructors();
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除失败:', error);
            this.$message.error('删除失败');
          }
        }
      }
    }
  };
  </script>
  
  <style scoped>
  .admin-instructor {
    padding: 20px;
  }
  
  .search-bar {
    margin-bottom: 20px;
  }
  
  .el-pagination {
    margin-top: 20px;
  }
  </style>